package com.zifan.sever.config.rabbitMQ;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zifan.sever.bean.MailLog;
import com.zifan.sever.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbitconfig
 * @author Zifan
 * @date 2021年05月20日20:23
 */
@Configuration
@Slf4j
public class RabbitConfig {
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private IMailLogService mailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调
         * data：消息唯一标识
         * ack：确认结果
         * cause：失败原因
         */
        rabbitTemplate.setConfirmCallback((data,ack,cause)->{
            //如果发消息的时候附带上了消息标识，那么这个就是标识
            String id = data.getId();
            if (ack){
                log.info("消息确认回调函数执行：消息被执行了！！{}=============>消息发送成功",id);
                //业务代码
                UpdateWrapper<MailLog> wrapper = new UpdateWrapper<>();
                //设置状态为1，投递成功
                wrapper.set("status",1);
                wrapper.eq("msgId",id);
                mailLogService.update(wrapper);

            }else {
                log.error("{}=============>消息发送失败",id);
                //业务代码
            }
        });

        /**
         * 消息失败回调
         */
        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routerKey)->{
            log.error("消息失败回调函数执行：消息失败了！！。。消息发送失败时的回调方法");
        });
        return rabbitTemplate;
    }
}
